﻿using LevelEditors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameConsole : Singleton<GameConsole>
{
    [CompilerGenerated]
    private static Application.LogCallback <>f__am$cache8;
    [CompilerGenerated]
    private static Dictionary<string, int> <>f__switch$map0;
    public static bool active;
    public static string command = string.Empty;
    private static List<string> commandHistory = new List<string>();
    private static List<string> lines = new List<string>();
    public static int maxLogLines = 0x3e7;
    private Vector2 scrollPos;
    private int selectedCommandIndex;
    public static Rect windowRect;

    public static void AddLine(string text, LogType logType = 3)
    {
        if (logType == LogType.Warning)
        {
            text = "[<b><color=yellow>WARNING</color></b>] " + text;
        }
        if (((logType == LogType.Error) || (logType == LogType.Exception)) || (logType == LogType.Assert))
        {
            text = "[<b><color=red>ERROR</color></b>] " + text;
        }
        if (logType == LogType.Log)
        {
            text = "[<b><color=#999999>LOG</color></b>] " + text;
        }
        text = text + "\n";
        lines.Add(text);
        if (lines.Count > maxLogLines)
        {
            lines.RemoveAt(0);
        }
    }

    private void Awake()
    {
        char[] separator = new char[] { '\n' };
        commandHistory = PlayerPrefs.GetString("Console.commandHistory").Split(separator).ToList<string>();
        if (<>f__am$cache8 == null)
        {
            <>f__am$cache8 = delegate (string condition, string stackTrace, LogType type) {
                AddLine(condition, type);
                if (((type == LogType.Error) || (type == LogType.Exception)) && (LevelEditor.Instance != null))
                {
                    active = true;
                }
            };
        }
        Application.logMessageReceived += <>f__am$cache8;
        windowRect = new Rect(10f, 40f, (float) (Screen.width / 2), (float) (Screen.height / 2));
    }

    public static void Clear()
    {
        lines.Clear();
    }

    private static void ClearEditorConsole()
    {
    }

    public bool DoString(string code)
    {
        try
        {
            string key = code.ToLower();
            if (key != null)
            {
                int num;
                if (<>f__switch$map0 == null)
                {
                    Dictionary<string, int> dictionary = new Dictionary<string, int>(1);
                    dictionary.Add("clear", 0);
                    <>f__switch$map0 = dictionary;
                }
                if (<>f__switch$map0.TryGetValue(key, out num) && (num == 0))
                {
                    Clear();
                }
            }
            return true;
        }
        catch (Exception exception)
        {
            Debug.LogException(exception);
        }
        return false;
    }

    [RuntimeInitializeOnLoadMethod]
    private static void Init()
    {
        Singleton<GameConsole>.Instance.enabled = true;
    }

    private void Log(object obj)
    {
        Debug.Log(obj);
    }

    private void OnDestroy()
    {
        PlayerPrefs.SetString("Console.commandHistory", string.Join("\n", commandHistory.ToArray()));
    }

    private void OnGUI()
    {
        <OnGUI>c__AnonStorey4E storeye = new <OnGUI>c__AnonStorey4E {
            <>f__this = this,
            e = Event.current
        };
        if ((storeye.e.type == EventType.KeyDown) && (storeye.e.keyCode == KeyCode.F2))
        {
            active = !active;
        }
        if (active)
        {
            GUI.skin.textArea.richText = true;
            windowRect = GUI.Window(this.GetHashCode(), windowRect, new GUI.WindowFunction(storeye.<>m__75), "Console", "Box");
            if ((storeye.e.type == EventType.KeyDown) && (storeye.e.keyCode == KeyCode.Return))
            {
                GUI.FocusControl("Console.commandTextField");
            }
        }
    }

    private void ReloadAssets()
    {
        Clear();
        ClearEditorConsole();
        if (LevelEditor.Instance != null)
        {
            UIProgressBar.Show("Loading...", 0f);
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
        AssetManager.Unload();
        if (IngameScene.isLoaded)
        {
            IngameScene.Reload();
        }
    }

    private void SetSelectedCommandIndexDelta(int value)
    {
        if (commandHistory.Count != 0)
        {
            this.selectedCommandIndex = Mathf.Clamp(this.selectedCommandIndex + value, 0, commandHistory.Count - 1);
            command = commandHistory[this.selectedCommandIndex];
        }
    }

    private void Update()
    {
        if ((!Debug.isDebugBuild ? ((LevelEditor.Instance != null) || LevelEditor.isSimulating) : true) && Input.GetKeyDown(KeyCode.F5))
        {
            this.ReloadAssets();
            AddLine("Reload assets", LogType.Log);
        }
    }

    public static bool isMouseOverConsoleGUI
    {
        get
        {
            return (active && windowRect.Contains(Input.mousePosition));
        }
    }

    [CompilerGenerated]
    private sealed class <OnGUI>c__AnonStorey4E
    {
        internal GameConsole <>f__this;
        internal Event e;

        internal void <>m__75(int id)
        {
            if ((Event.current.keyCode == KeyCode.Return) && !string.IsNullOrEmpty(GameConsole.command))
            {
                GameConsole.AddLine("[CMD]" + GameConsole.command, LogType.Log);
                this.<>f__this.DoString(GameConsole.command);
                GameConsole.commandHistory.Add(GameConsole.command);
                if (GameConsole.commandHistory.Count > 30)
                {
                    GameConsole.commandHistory.RemoveAt(0);
                }
                GameConsole.command = string.Empty;
                this.<>f__this.scrollPos.y = float.PositiveInfinity;
            }
            if (GUI.Button(new Rect(GameConsole.windowRect.width - 20f, 0f, 20f, 20f), "X", "Label"))
            {
                GameConsole.active = false;
            }
            GUILayout.Space(20f);
            this.<>f__this.scrollPos = GUILayout.BeginScrollView(this.<>f__this.scrollPos, new GUILayoutOption[0]);
            GUI.SetNextControlName("Console.logTextArea");
            for (int i = 0; i < GameConsole.lines.Count; i++)
            {
                GUILayout.TextField(GameConsole.lines[i], "Label", new GUILayoutOption[0]);
            }
            GUILayout.EndScrollView();
            if ((this.e.type == EventType.KeyDown) && (this.e.keyCode == KeyCode.UpArrow))
            {
                this.<>f__this.SetSelectedCommandIndexDelta(1);
            }
            if ((this.e.type == EventType.KeyDown) && (this.e.keyCode == KeyCode.DownArrow))
            {
                this.<>f__this.SetSelectedCommandIndexDelta(-1);
            }
            if ((this.e.type == EventType.KeyDown) && (this.e.keyCode == KeyCode.Escape))
            {
                GUI.FocusControl(string.Empty);
            }
            GUI.SetNextControlName("Console.commandTextField");
            if (GameConsole.command == null)
            {
                GameConsole.command = string.Empty;
            }
            GameConsole.command = GUILayout.TextField(GameConsole.command, new GUILayoutOption[0]);
            GUI.DragWindow();
        }
    }
}

